package dianmobile.eistarandroid.ui.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dianmobile.eistarandroid.ByhhAndroidApplication;
import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.ArticleDetailEntity;
import dianmobile.eistarandroid.network.request.GetOneArticleRequest;
import dianmobile.eistarandroid.network.request.RepublishRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.ui.Adapter.ViewPostListAdapter;
import dianmobile.eistarandroid.ui.views.SwipeActivity;
import dianmobile.eistarandroid.utils.ConstantsData;
import dianmobile.eistarandroid.utils.HandleString;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

public class ViewPostActivity extends SwipeActivity {

    private List<ArticleDetailEntity> articleList = new ArrayList<>();
    private ImageButton btnBack;
    private TextView tvActivityTitle;
    private ImageButton btnWriteReply;
    private ZrcListView listView;
    private ViewPostListAdapter adapter;

    private PopupWindow popupWindow;

    private String boardName;
    private String fileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().add(this);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_view_post);

        Intent intent = getIntent();
        fileName = intent.getStringExtra(ConstantsData.EXTRA_FILE_NAME);
        boardName = intent.getStringExtra(ConstantsData.EXTRA_BOARD_NAME);

        listView = (ZrcListView)findViewById(R.id.lv_view_post);
        setPullToRefresh();
        adapter = new ViewPostListAdapter(ViewPostActivity.this, articleList, boardName);
        listView.setAdapter(adapter);
        listView.refresh();
//        getData();

        btnBack = (ImageButton)findViewById(R.id.btn_back);
        tvActivityTitle = (TextView)findViewById(R.id.tv_activity_title);
        btnWriteReply = (ImageButton)findViewById(R.id.btn_send);
        tvActivityTitle.setText("帖子详情");
        TitleClickListener titleClickListener = new TitleClickListener();
        btnBack.setOnClickListener(titleClickListener);
        btnWriteReply.setOnClickListener(titleClickListener);
    }

    @Override
    public void onDestroy() {
        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().remove(this);
        if(popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (2 == requestCode && resultCode == RESULT_OK) {
            getData();
        }
    }
    private void getData(){
        Map<String, String> params = new HashMap<>();
        params.put(ConstantsData.EXTRA_BOARD_NAME, boardName);
        params.put(ConstantsData.EXTRA_FILE_NAME, fileName);

        GetOneArticleRequest.execute(ViewPostActivity.this, params, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                if (error != null) {
                    listView.setRefreshFail("网络错误");
                } else {
                    boolean isFirstShow = false;    //只有第一次加载时才跳转到指定item，后来的刷新不跳转
                    if (articleList.size() == 0) {
                        isFirstShow = true;
                    }
                    articleList.clear();
                    articleList.addAll((List<ArticleDetailEntity>) result.get(ConstantsData.ARTICLE_LIST));
                    adapter.notifyDataSetChanged();
                    listView.setRefreshSuccess();
                    if (isFirstShow) {
                        int position = 0;
                        for (int i = 0; i < articleList.size(); i++) {
                            if (articleList.get(i).getFileName().equals(fileName)) {
                                position = (i == 0) ? 0 : (i + 1);
                            }
                        }
                        listView.setSelection(position);
                    }
                }
            }
        });
    }

    private void setPullToRefresh() {
        SimpleHeader header = new SimpleHeader(this);
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        listView.setHeadable(header);
//
//        SimpleFooter footer = new SimpleFooter(this);
//        footer.setCircleColor(0xff33bbee);
//        listView.setFootable(footer);

        listView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                getData();
            }
        });
    }

    /**
     * 初始化popupWindow，并添加点击事件
     */
    public void initPopupWindow() {
        View popupView = getLayoutInflater().inflate(R.layout.popup_view, null);
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setAnimationStyle(R.style.Animation_AppCompat_DropDownUp);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(true);
        popupView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });

        Button reply = (Button)popupView.findViewById(R.id.btn_reply);
        Button republish = (Button)popupView.findViewById(R.id.btn_republish);
        Button share = (Button)popupView.findViewById(R.id.btn_share);
        Button edit = (Button)popupView.findViewById(R.id.btn_edit);
        Button delete = (Button)popupView.findViewById(R.id.btn_delete);

        reply.setOnClickListener(new PopupWindowClickListener());
        republish.setOnClickListener(new PopupWindowClickListener());
        share.setOnClickListener(new PopupWindowClickListener());
        edit.setOnClickListener(new PopupWindowClickListener());
        delete.setOnClickListener(new PopupWindowClickListener());
    }

    /**
     * 转帖
     * @param srcBoard 转自某版
     * @param fileName 要转的帖子
     */
    private void republish(final String srcBoard, final String fileName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final EditText toBoard = new EditText(this);
        builder.setTitle("转载到")
                .setView(toBoard)
                .setPositiveButton("发布", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (toBoard.getText().toString().equals("")) {
                            dialog.dismiss();
                            return;
                        }
                        Map<String, String> params = new HashMap<>();
                        params.put("srcBoard", srcBoard);
                        params.put("fileName", fileName);
                        params.put("toBoard", toBoard.getText().toString());
                        RepublishRequest.execute(ViewPostActivity.this, params, new RequestCallback() {
                            @Override
                            public void onResult(Map<String, Object> result, String error) {
                                if (error != null) {
                                    Toast.makeText(ViewPostActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                                } else {
                                    if (result.containsKey(ConstantsData.ERROR_RESULT)) {
                                        Toast.makeText(ViewPostActivity.this, "转发失败："
                                                +result.get(ConstantsData.ERROR_RESULT), Toast.LENGTH_SHORT);
                                    } else {
                                        Toast.makeText(ViewPostActivity.this, "已转至 "
                                                +toBoard.getText().toString()+" 版", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        });
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    }
    class TitleClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_back:
                    ViewPostActivity.this.finish();
                    break;
                case R.id.btn_send:
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    } else {
                        initPopupWindow();
                        popupWindow.showAsDropDown(v, 0, 0);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    class PopupWindowClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            switch (v.getId()) {
                case R.id.btn_reply:
                    Intent intent = new Intent(ViewPostActivity.this, PostArticleActivity.class);
                    intent.putExtra(ConstantsData.EXTRA_POST_TYPE, ConstantsData.POST_TYPE_REPLY);
                    intent.putExtra(ConstantsData.EXTRA_BOARD_NAME, boardName);
                    intent.putExtra(ConstantsData.REPLY_TITLE, articleList.get(0).getArticleTitle());
                    intent.putExtra(ConstantsData.EXTRA_FILE_NAME, fileName);

                    intent.putExtra(ConstantsData.REPLY_SUMMARY, "【 在 "+articleList.get(0).getAuthorName()+" 的大作中提到: 】\n"
                            + HandleString.getSummary(articleList.get(0).getArticleDetail()));
                    startActivityForResult(intent, 2);
                    break;
                case R.id.btn_republish:
                    republish(boardName, fileName);
                    break;
                case R.id.btn_share:
                    String url = "http://dian.hust.edu.cn:81/bbsnewtcon?board="+boardName+"&file=" + fileName;
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_TEXT, "我在白云黄鹤BBS上看到了这篇非常好的文章，快来看看吧~\n"+url);
                    shareIntent.setType("text/plain");
                    startActivity(Intent.createChooser(shareIntent, "分享至"));
                    break;
                case R.id.btn_edit:
                    break;
                case R.id.btn_delete:
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        if ((popupWindow != null) && (popupWindow.isShowing())){
            popupWindow.dismiss();
        }else {
            this.finish();
        }
    }
}
